import common from './common.js'

export default {
	connecting: false,
	socketUrl: 'ws://' + common.remoteServer,
	async initSocket() {
		//如果连接中或者是已连接状态则停止
		if (this.connecting) {
			return;
		}
		this.connecting = true;
		this.connection();
		try {
			await Promise.race([
				new Promise((res, rej) => {
					uni.onSocketOpen(() => {
						res();
					});
				}),
				new Promise((res, rej) => {
					setTimeout(() => {
						rej('无法连接服务器进行通信');
					}, 3000);
				})
			]);
			common.connected = true;
			return Promise.resolve();
		} catch (e) {
			return Promise.reject(e);
		} finally {
			this.connecting = false;
		}
	},
	//连接
	connection() {
		uni.connectSocket({
			url: `${this.socketUrl}?token=${common.token}&id=${uni.clientInfo.clientid}`
		});
	},
}
